import classNames from 'classnames';
import Taro, { usePullDownRefresh, useRouter } from '@tarojs/taro';
import { useRequest } from 'ahooks';
import { useEffect, useMemo, useRef, useState } from 'react';
import {
    AreaSelect,
    CinemaCard,
    CustomNavBar,
    DateListRefType,
    EmptyCard,
    MovieTitle,
    SearchBar,
} from '@/components';
import { PositionType, useCityStore } from '@/common/hox/cityStore';
import { useUserStore } from '@/common/hox/userStore';
import { Loading } from '@/components';
import styles from './index.module.less';
import { useMovieStore } from '@/common/hox/movieStore';
import { usePageShow } from '@/common/hook/usePage';
import { getCinemaList, getMovieShowDate } from '@/service';
import appConfig from '@/utils/appConfig';
import { PageUrlMap } from '@/utils/enum';
import { PageUrlEnum } from '@/utils/enum';
import dayjs from 'dayjs';
type RouterParamType = {
    movieId: string;
};
type CinemaListPagePropsType = {
    chooseCityUrl?: string;
    TheaterDetail?: string;
    showCommission?: boolean;
};
function CinemaListPage(props: CinemaListPagePropsType) {
    const { userInfo } = useUserStore();
    const {
        chooseCityUrl = PageUrlMap.get(PageUrlEnum.MovieChooseCity),
        TheaterDetail = PageUrlMap.get(PageUrlEnum.TheaterDetail),
    } = props;
    const { movieLocation, position, awaitInitialized, isReady } = useCityStore();
    const {
        cinema: { setCinemaInfo },
        combination: { combinationInfo },
    } = useMovieStore((store) => [store.cinema.setCinemaInfo, store.combination.combinationInfo]);
    const { params } = useRouter<RouterParamType>();
    const { movieId } = params;
    const dataListRef = useRef<DateListRefType>(null);
    const [loadingInitialData, setLoadingInitialData] = useState(true);
    // 无法获取定位及城市的时候，跳转选择城市
    const [chooseCityAlertShow, setChooseCityAlertShow] = useState(false);
    usePageShow(async () => {
        setLoadingInitialData(true);
        await awaitInitialized(); // 等待位置和城市数据加载完成
        setLoadingInitialData(false);
        if (chooseCityUrl && chooseCityAlertShow && !position && !movieLocation?.cityId) {
            Taro.showModal({
                title: '提示',
                content: '请选择城市',
                confirmText: '确定',
                success: (res) => {
                    if (res.confirm) {
                        Taro.navigateTo({ url: chooseCityUrl });
                    } else {
                        Taro.navigateBack();
                    }
                },
            });
        }
    });

    // 处理导航逻辑
    useEffect(() => {
        if (!isReady) return;

        if (chooseCityUrl && !position && !movieLocation?.cityId) {
            setTimeout(() => {
                setChooseCityAlertShow(true);
                Taro.navigateTo({ url: chooseCityUrl });
            }, 100);
        }
    }, [movieLocation, position, isReady]); // 添加 isReady 依赖

    // 影院列表
    const [searchValue, setSearchValue] = useState<string>();
    const [selectDate, setSelectDate] = useState<string>();
    // 点击影院
    const handleCinemaClick = (item, cinemaCode) => {
        if (userInfo?.userId && userInfo?.mobile) {
            setCinemaInfo(item);
            TheaterDetail &&
                Taro.navigateTo({
                    url: `${TheaterDetail}?cinemaId=${cinemaCode}&date=${selectDate}`,
                });
        } else {
            Taro.navigateTo({ url: `/pages/login/index` });
        }
    };
    const getCinemaListApi = useRequest(
        () => {
            setSelectDate(dayjs().format('YYYY-MM-DD'));
            return getCinemaList({
                cityId: movieLocation?.cityId,
                longitude: (position as PositionType)?.longitude,
                latitude: (position as PositionType)?.latitude,
            });
        },
        {
            ready: Boolean(movieLocation),
            refreshDeps: [movieLocation],
            onBefore: () => Taro.showLoading({
                title:'加载中'
            }),
            onFinally: () => Taro.hideLoading(),
        }
    );
    const showMovieCinema = useMemo(() => {
        const data = getCinemaListApi.data?.list || [];
        if (!searchValue) return data;
        return data.filter(
            (item) =>
                item.cinemaName.includes(searchValue) || item.cinemaAddress.includes(searchValue)
        );
    }, [getCinemaListApi.data, searchValue]);

    usePullDownRefresh(async () => {
        await getCinemaListApi?.runAsync();
        Taro.stopPullDownRefresh();
    });
    const getMovieShowDateApi = useRequest(
        () =>
            getMovieShowDate({
                filmId: movieId,
                cityId: movieLocation?.cityId,
            }),
        {
            ready: Boolean(movieId && movieLocation),
            refreshDeps: [movieLocation],
            onSuccess: (res) => {
                if (res.showTimes.length === 0) {
                    Taro.showModal({
                        title: '提示',
                        content: '当前城市电影没有场次，请选择其他电影或城市',
                        confirmText: '我知道了',
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                Taro.navigateBack();
                            } else if (res.cancel) {
                            }
                        },
                    });
                }
            },
            onError: () => {},
        }
    );
    const detail = useMemo(() => getMovieShowDateApi.data, [getMovieShowDateApi.data]);
    if (loadingInitialData || !isReady) {
        return <Loading />;
    }
    return (
        <div className={styles.page}>
            <CustomNavBar title={detail?.name || '影院'} />
            {detail && <MovieTitle data={detail} useCombination={!!combinationInfo} />}
            <div className={styles.searchWrapper}>
                <AreaSelect
                    handleCityClick={() => chooseCityUrl && Taro.navigateTo({ url: chooseCityUrl })}
                >
                    <SearchBar
                        className={classNames(styles.searchBar, 'light')}
                        value={searchValue}
                        onChange={setSearchValue}
                        placeholder="影院名称/地址"
                    />
                </AreaSelect>
            </div>
            {!getCinemaListApi.loading ? (
                <div className={styles.cinemaContent}>
                    {getCinemaListApi.data?.list?.length === 0 ? (
                        <EmptyCard
                            selectDate={selectDate}
                            handleClick={() => dataListRef.current?.selectNext()}
                        />
                    ) : (
                        showMovieCinema.map((item) => {
                            const { cinemaCode } = item;
                            if (appConfig.movieConfig?.priceFormatter) {
                                item.price = appConfig.movieConfig.priceFormatter(item.price);
                            }
                            return (
                                <CinemaCard
                                    data={item}
                                    key={cinemaCode}
                                    showPrice={false}
                                    isCombination={!!combinationInfo}
                                    onClick={() => handleCinemaClick(item, cinemaCode)}
                                />
                            );
                        })
                    )}
                </div>
            ) : null}
        </div>
    );
}

export default CinemaListPage;
